<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入应用名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="codeGenType">
        <el-select v-model="queryParams.codeGenType" placeholder="请选择代码生成类型" clearable>
          <el-option
            v-for="dict in generation_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部署标识" prop="deployKey">
        <el-input
          v-model="queryParams.deployKey"
          placeholder="请输入部署标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option
            v-for="dict in priority"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建用户" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入创建用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ai:app:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ai:app:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ai:app:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ai:app:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange" :row-style="{ height: '80px' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="应用名称" align="center" prop="appName" />
      <el-table-column label="应用封面" align="center" prop="cover" width="200">
        <template #default="scope">
          <div v-if="scope.row.cover" class="cover-container">
            <img 
              :src="scope.row.cover" 
              :alt="scope.row.appName + ' 封面'" 
              class="app-cover"
              @click="showCoverPreview(scope.row.cover)"
            />
          </div>
          <div v-else class="no-cover">
            <el-icon size="20"><Picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="应用初始化提示词" align="center" prop="initPrompt" width="200">
        <template #default="scope">
          <div v-if="scope.row.initPrompt" class="prompt-container">
            <span 
              class="prompt-text" 
              :title="scope.row.initPrompt"
              @click="showPromptDetail(scope.row.initPrompt)"
            >
              {{ truncateText(scope.row.initPrompt, 30) }}
            </span>
          </div>
          <div v-else class="no-prompt">
            <span class="text-gray-400">暂无</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="模板类型" align="center" prop="codeGenType">
        <template #default="scope">
          <dict-tag :options="generation_type" :value="scope.row.codeGenType"/>
        </template>
      </el-table-column>
      <el-table-column label="部署标识" align="center" prop="deployKey" />
      <el-table-column label="部署时间" align="center" prop="deployedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deployedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template #default="scope">
          <dict-tag :options="priority" :value="scope.row.priority"/>
        </template>
      </el-table-column>
      <el-table-column label="创建用户" align="center" prop="userId" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ai:app:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ai:app:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option
              v-for="dict in priority"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 应用封面预览弹窗 -->
    <el-dialog
      v-model="coverPreviewVisible"
      title="应用封面预览"
      width="600px"
      center
      :before-close="closeCoverPreview"
    >
      <div class="cover-preview-container">
        <img 
          :src="previewCoverUrl" 
          alt="应用封面预览" 
          class="preview-cover-image"
        />
      </div>
    </el-dialog>

    <!-- 提示词详情弹窗 -->
    <el-dialog
      v-model="promptDetailVisible"
      title="应用初始化提示词"
      width="800px"
      center
      :before-close="closePromptDetail"
    >
      <div class="prompt-detail-container">
        <div class="prompt-content">
          {{ currentPrompt }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="App">
import { listApp, getApp, delApp, addApp, updateApp } from "@/api/ai/app"
import { Picture } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { generation_type, priority } = proxy.useDict('generation_type', 'priority')

const appList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 图片预览相关
const coverPreviewVisible = ref(false)
const previewCoverUrl = ref('')

// 提示词详情相关
const promptDetailVisible = ref(false)
const currentPrompt = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appName: null,
    initPrompt: null,
    codeGenType: null,
    deployKey: null,
    priority: null,
    userId: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询应用列表 */
function getList() {
  loading.value = true
  listApp(queryParams.value).then(response => {
    appList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    appName: null,
    cover: null,
    initPrompt: null,
    codeGenType: null,
    deployKey: null,
    deployedTime: null,
    priority: null,
    userId: null,
    createTime: null,
    updateTime: null,
    deleted: null
  }
  proxy.resetForm("appRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加应用"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getApp(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改应用"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateApp(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addApp(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除应用编号为"' + _ids + '"的数据项？').then(function() {
    return delApp(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ai/app/export', {
    ...queryParams.value
  }, `app_${new Date().getTime()}.xlsx`)
}

// 文本截断函数
function truncateText(text, maxLength) {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 显示应用封面预览
function showCoverPreview(coverUrl) {
  previewCoverUrl.value = coverUrl
  coverPreviewVisible.value = true
}

// 关闭应用封面预览
function closeCoverPreview() {
  coverPreviewVisible.value = false
  previewCoverUrl.value = ''
}

// 显示提示词详情
function showPromptDetail(prompt) {
  currentPrompt.value = prompt
  promptDetailVisible.value = true
}

// 关闭提示词详情
function closePromptDetail() {
  promptDetailVisible.value = false
  currentPrompt.value = ''
}

getList()
</script>

<style scoped>
/* 表格样式 */
:deep(.el-table .el-table__row) {
  height: 80px !important;
}

:deep(.el-table .el-table__cell) {
  padding: 15px 0 !important;
  vertical-align: middle;
}

/* 应用封面样式 */
.cover-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.app-cover {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.app-cover:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.no-cover {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 70px;
  height: 70px;
  background: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  color: #999;
}

/* 提示词样式 */
.prompt-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.prompt-text {
  cursor: pointer;
  color: #606266;
  transition: color 0.3s ease;
  word-break: break-all;
  line-height: 1.4;
}

.prompt-text:hover {
  color: #409eff;
}

.no-prompt {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 图片预览弹窗样式 */
.cover-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 400px;
}

.preview-cover-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 提示词详情弹窗样式 */
.prompt-detail-container {
  padding: 20px 0;
}

.prompt-content {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  color: #303133;
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-cover {
    width: 60px;
    height: 60px;
  }
  
  .no-cover {
    width: 60px;
    height: 60px;
  }
  
  .prompt-content {
    font-size: 13px;
    padding: 15px;
  }
  
  :deep(.el-table .el-table__row) {
    height: 70px !important;
  }
  
  :deep(.el-table .el-table__cell) {
    padding: 12px 0 !important;
  }
}
</style>
